import { useEffect, useState, useRef } from 'preact/hooks';
import { isConnected, deviceInfo } from '../app';
import firmwareVersionToString from '../global';

// 定义设备信息类型
/** @typedef {{ firmwareVersion: number }} DeviceInfo */

export default function Sidebar({ onRouteChange }) {
  const [currentPath, setCurrentPath] = useState(window.location.pathname);
  const [isCollapsed, setIsCollapsed] = useState(false);
  const heartbeatTimer = useRef(null);
  const heartbeatTimeout = useRef(null);
  const isHeartbeatPending = useRef(false);

  const toggleSidebar = () => {
    setIsCollapsed(!isCollapsed);
  };

  // 心跳检测函数
  const checkHeartbeat = async () => {
    // 如果上一次心跳还未完成，则不发送新的心跳
    if (isHeartbeatPending.current) {
      return;
    }

    isHeartbeatPending.current = true;

    try {
      const controller = new AbortController();
      heartbeatTimeout.current = setTimeout(() => {
        controller.abort();
        isConnected.value = false;
      }, 3000); // 3秒超时

      const response = await fetch("/api/heartbeat", {
        signal: controller.signal
      });

      if (response.status === 403) {
        isConnected.value = false;
      } else {
        const data = await response.json();
        isConnected.value = true;
        deviceInfo.value = data;
      }
    } catch (error) {
      if (error.name === 'AbortError') {
        console.log('心跳检测超时');
        isConnected.value = false;
      } else {
        console.error('心跳检测错误:', error);
        isConnected.value = false;
      }
    } finally {
      clearTimeout(heartbeatTimeout.current);
      isHeartbeatPending.current = false;
    }
  };

  const menuItems = [
    { 
      path: '/', 
      title: '欢迎', 
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
        </svg>
      )
    },
    { 
      path: '/device-status', 
      title: '设备状态', 
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
        </svg>
      )
    },
    { 
      path: '/led-control', 
      title: 'LED 控制', 
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
        </svg>
      )
    },
    { 
      path: '/buzzer-control', 
      title: '蜂鸣器控制', 
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3" />
        </svg>
      )
    },
    { 
      path: '/settings', 
      title: '设置', 
      icon: (
        <svg className="w-5 h-5" viewBox="0 0 1024 1024">
          <path d="M416.4 958h191.2V849.7c0-12.7 6.4-25.5 19.1-31.9 31.9-12.7 63.7-31.9 89.2-51 12.7-6.4 25.5-6.4 38.2 0l95.6 57.3 95.6-165.7-95.6-57.3C837 588.5 830.6 575.7 837 563c0-19.1 6.4-31.9 6.4-51s0-31.9-6.4-51c0-12.7 6.4-25.5 12.7-31.9l95.6-57.3-95.6-165.7-95.6 57.3c-12.7 6.4-25.5 6.4-38.2 0-25.5-19.1-57.3-38.2-89.2-51-12.7-12.7-19.1-25.5-19.1-38.2V66H416.4v108.3c0 12.7-6.4 25.5-19.1 31.9-31.9 12.7-63.7 31.9-89.2 51-12.7 6.4-25.5 6.4-38.2 0l-95.6-51-95.6 165.6 95.6 57.3c12.7 6.4 19.1 19.1 12.7 31.9 0 19.1-6.4 31.9-6.4 51s0 31.9 6.4 51c6.4 12.7 0 25.5-12.7 31.9l-95.6 57.3 95.6 165.7 95.6-57.3c12.7-6.4 25.5-6.4 38.2 0 25.5 19.1 57.3 38.2 89.2 51 12.7 6.4 19.1 19.1 19.1 31.9V958z" fill="currentColor" />
        </svg>
      )
    }
  ];

  useEffect(() => {
    // 获取当前路径
    const updateCurrentPath = () => {
      setCurrentPath(window.location.pathname);
    };

    // 初始化时设置当前路径
    updateCurrentPath();

    // 监听路由变化
    window.addEventListener('popstate', updateCurrentPath);
    
    // 启动心跳检测
    checkHeartbeat(); // 立即执行一次
    heartbeatTimer.current = setInterval(checkHeartbeat, 1000); // 每秒执行一次

    // 清除定时器和事件监听
    return () => {
      clearInterval(heartbeatTimer.current);
      clearTimeout(heartbeatTimeout.current);
      window.removeEventListener('popstate', updateCurrentPath);
    };
  }, []); // 空依赖数组确保定时器只在组件挂载时启动一次

  const handleClick = (path) => (e) => {
    if (path !== currentPath) {
      if (onRouteChange) {
        onRouteChange(e);
        if (!e.defaultPrevented) {
          setCurrentPath(path);
        }
      } else {
        setCurrentPath(path);
      }
    }
  };

  return (
    <div className={`bg-gray-900 min-h-screen shadow-lg ${isCollapsed ? 'w-16' : 'w-64'} transition-all duration-300 ease-in-out relative`}>
      <div className={`p-4 border-b border-gray-800 transition-all duration-300 ${isCollapsed ? 'opacity-0 h-0 p-0 overflow-hidden border-none' : 'opacity-100'}`}>
        <div className="flex flex-col">
          <div className="flex items-center space-x-2">
            <div className="w-1 h-5 bg-blue-500"></div>
            <h1 className="font-['Orbitron'] text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-blue-600 tracking-wider">
              HPM5E-EC-DEV
            </h1>
          </div>
          <div className="mt-0.5 ml-3 flex items-center">
            <span className="text-[10px] text-gray-400 tracking-[0.2em] font-light">CONTROL PANEL</span>
          </div>
        </div>
        <div className="mt-2 space-y-1.5">
          <div className="flex items-center">
            <div className={`w-1.5 h-1.5 rounded-full mr-2 ${isConnected.value ? 'bg-green-500' : 'bg-red-500'} animate-pulse`}></div>
            <span className="text-xs text-gray-400">{isConnected.value ? '在线' : '离线'}</span>
          </div>
          <div className="flex items-center text-xs text-gray-400">
            <svg className="w-3.5 h-3.5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
            </svg>
            <span>固件版本：{
              (() => {
                const info = /** @type {DeviceInfo} */ (/** @type {unknown} */ (deviceInfo.value));
                return info?.firmwareVersion ? firmwareVersionToString(info.firmwareVersion) : '0.0.0';
              })()
            }</span>
          </div>
        </div>
      </div>

      <nav className={`${isCollapsed ? 'mt-4' : 'mt-2'}`}>
        {menuItems.map((item) => (
          <a
            key={item.path}
            href={item.path}
            className={`flex items-center h-10 px-4 text-gray-300 hover:bg-gray-800 transition-colors duration-200 ${
              currentPath === item.path ? 'bg-gray-800 text-white' : ''
            }`}
            onClick={handleClick(item.path)}
          >
            <div className={`flex items-center justify-center ${isCollapsed ? 'w-full' : 'w-6 mr-3'}`}>
              <div className="w-5 h-5">
                {item.icon}
              </div>
            </div>
            <span className={`text-sm transition-opacity duration-300 whitespace-nowrap ${
              isCollapsed ? 'opacity-0 w-0 overflow-hidden' : 'opacity-100'
            }`}>
              {item.title}
            </span>
          </a>
        ))}
      </nav>

      <button 
        className="absolute bottom-4 left-0 right-0 mx-auto w-10 h-10 flex items-center justify-center rounded-full bg-gray-700 text-gray-300 hover:bg-gray-600 hover:text-white transition-colors duration-200" 
        onClick={toggleSidebar}
      >
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d={isCollapsed ? "M13 5l7 7-7 7M5 5l7 7-7 7" : "M11 19l-7-7 7-7M19 19l-7-7 7-7"} />
        </svg>
      </button>
    </div>
  );
}